package link.chengguo.orangemall.pay.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import link.chengguo.orangemall.enums.*;
import link.chengguo.orangemall.exception.ApiMallPlusException;
import link.chengguo.orangemall.oms.entity.OmsOrder;
import link.chengguo.orangemall.oms.entity.OmsOrderItem;
import link.chengguo.orangemall.oms.entity.OmsOrderOperateHistory;
import link.chengguo.orangemall.oms.mapper.OmsOrderMapper;
import link.chengguo.orangemall.oms.service.IOmsOrderItemService;
import link.chengguo.orangemall.oms.service.IOmsOrderOperateHistoryService;
import link.chengguo.orangemall.oms.service.IOmsOrderService;
import link.chengguo.orangemall.oms.vo.OrderParam;
import link.chengguo.orangemall.pay.service.PayService;
import link.chengguo.orangemall.pms.entity.PmsGifts;
import link.chengguo.orangemall.pms.service.IPmsGiftsService;
import link.chengguo.orangemall.shms.service.IShmsShopAccountService;
import link.chengguo.orangemall.shms.service.IShmsShopBillLogService;
import link.chengguo.orangemall.sms.entity.SmsGroup;
import link.chengguo.orangemall.sms.mapper.SmsGroupMapper;
import link.chengguo.orangemall.sms.service.*;
import link.chengguo.orangemall.ums.entity.UmsIntegrationChangeHistory;
import link.chengguo.orangemall.ums.entity.UmsMember;
import link.chengguo.orangemall.ums.entity.UmsMemberBlanceLog;
import link.chengguo.orangemall.ums.mapper.UmsIntegrationChangeHistoryMapper;
import link.chengguo.orangemall.ums.service.IUmsMemberBlanceLogService;
import link.chengguo.orangemall.ums.service.IUmsMemberService;
import link.chengguo.orangemall.ums.service.RedisService;
import link.chengguo.orangemall.utils.CommonResult;
import link.chengguo.orangemall.utils.ValidatorUtils;
import link.chengguo.orangemall.vo.Rediskey;
import link.chengguo.orangemall.enums.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PayServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements PayService {


    @Resource
    private RedisService redisService;
    @Resource
    private IOmsOrderService orderService;
    @Resource
    private IUmsMemberBlanceLogService memberBlanceLogService;
    @Resource
    private IOmsOrderItemService orderItemService;
    @Resource
    private IUmsMemberService memberService;
    @Resource
    private SmsGroupMapper groupMapper;
    @Resource
    private IPmsGiftsService giftsService;
    @Resource
    private UmsIntegrationChangeHistoryMapper integrationChangeHistoryMapper;
    @Autowired
    private IOmsOrderOperateHistoryService orderOperateHistoryService;
    @Resource
    private IShmsShopAccountService shopAccountService;
    @Resource
    private IShmsShopBillLogService shopBillLogService;



    @Override
    public String wxPayNotifyManage(String out_trade_no) {


        return null;
    }

    @Transactional
    @Override
    public boolean updateOrderStatus(OmsOrder omsOrder) {
       this.updateOrderStatus2(omsOrder);
       //添加账单记录
        shopBillLogService.addShopBillLog(omsOrder, BillOrderType.OrderPay.getValue());
        return true;
    }

    @Override
    public boolean updateOrderStatus2(OmsOrder omsOrder) {
        if (omsOrder.getSendType().intValue()== SendType.CodeBuy.getValue()){//扫码购
            omsOrder.setStatus(OrderStatus.Ensured.getValue());
            omsOrder.setVerifyStatus(VerifyStatus.WaitVerify.getValue());//进入待核销状态
        }else if (omsOrder.getSendType().intValue()==SendType.Express.getValue()){//物流配送
            omsOrder.setStatus(OrderStatus.Ensured.getValue());
            omsOrder.setExpressStatus(ExpressStatus.ToDeliver.getValue());//进入待发货状态
        }else{//其他的均需要商家确认，后续如果需要自动接单，需在此处调整
            omsOrder.setStatus(OrderStatus.WaitEnsure.getValue());//订单状态，待确认
        }
        omsOrder.setPayStatus(PayStatus.Paid.getValue());//支付状态：已支付
        omsOrder.setPaymentTime(new Date());
        return  orderService.updateById(omsOrder);
    }

    @Transactional
    @Override
    public OmsOrder blancePay(OmsOrder order) {
        UmsMember userDO = memberService.getNewCurrentMember();
        if (order.getPayAmount().compareTo(userDO.getBlance()) > 0) {
            throw new ApiMallPlusException("余额不足！");
        }
        this.updateOrderStatus2(order);
//        order.setStatus(OrderStatus.TO_DELIVER.getValue());
//        order.setPayType(AllEnum.OrderPayType.balancePay.code());
//        order.setPaymentTime(new Date());
//        orderService.updateById(order);
        if (ValidatorUtils.notEmpty(order.getGroupId())) {
            SmsGroup group = new SmsGroup();
            group.setId(order.getGroupId());
            group.setPeoples(group.getPeoples() - 1);
            groupMapper.updateById(group);
        }
        if (order.getPayAmount().compareTo(BigDecimal.ZERO) < 0) {
            order.setPayAmount(new BigDecimal("0.01"));
        }
        userDO.setBlance(userDO.getBlance().subtract(order.getPayAmount()));
        memberService.updateById(userDO);
        UmsMemberBlanceLog blog = new UmsMemberBlanceLog();
        blog.setMemberId(userDO.getId());
        blog.setCreateTime(new Date());
        blog.setNote("支付订单：" + order.getId());
        blog.setPrice(order.getPayAmount());
        blog.setType(1);
        memberBlanceLogService.save(blog);
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(order.getId());
        history.setCreateTime(new Date());
        history.setOperateMan("shop");
        history.setPreStatus(OrderStatus.INIT.getValue());
        history.setOrderStatus(OrderStatus.TO_DELIVER.getValue());
        history.setNote("余额支付");
        orderOperateHistoryService.save(history);
        memberService.addIntegration(userDO.getId(), order.getPayAmount().multiply(new BigDecimal("0.1")).intValue(), 1, "余额支付添加积分", AllEnum.ChangeSource.order.code(), userDO.getUsername());
        //商家账户余额操作,统一在结算时候处理
//        shopAccountService.updateShopAccountFrozenBalance(0, AccountChangeType.OrderPay.getValue(),order.getShopId(),order.getPayAmount(),"订单支付："+order.getId());
        shopBillLogService.addShopBillLog(order,BillOrderType.OrderPay.getValue());
        return order;
    }

    @Override
    @Transactional
    public Object jifenPay(OrderParam orderParam) {
        UmsMember member = memberService.getById(memberService.getNewCurrentMember().getId());
        PmsGifts gifts = giftsService.getById(orderParam.getGoodsId());
        if (gifts.getPrice().intValue() > member.getIntegration()) {
            return new CommonResult().failed("积分不足！");
        } else {
            // 插入订单
            OmsOrderItem orderItem = new OmsOrderItem();
            orderItem.setProductId(orderParam.getGoodsId());
            orderItem.setProductName(gifts.getTitle());
            orderItem.setProductPic(gifts.getIcon());
            orderItem.setProductPrice(gifts.getPrice());
            orderItem.setProductQuantity(1);
            orderItem.setProductCategoryId(gifts.getCategoryId());
            List<OmsOrderItem> omsOrderItemList = new ArrayList<>();
            omsOrderItemList.add(orderItem);
            OmsOrder order = new OmsOrder();
            orderService.createOrderObj(order, orderParam, member, omsOrderItemList, null);
            order.setOrderType(AllEnum.OrderType.JIFEN.code());
            order.setStatus(OrderStatus.TO_DELIVER.getValue());
            order.setPayType(AllEnum.OrderPayType.jifenPay.code());
            orderService.save(order);
            orderItem.setOrderId(order.getId());
            orderItemService.save(orderItem);

            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(order.getId());
            history.setCreateTime(new Date());
            history.setOperateMan("shop");
            history.setPreStatus(OrderStatus.INIT.getValue());
            history.setOrderStatus(OrderStatus.TO_DELIVER.getValue());
            history.setNote("积分兑换");
            orderOperateHistoryService.save(history);

            //修改会员积分
            member.setIntegration(member.getIntegration() - gifts.getPrice().intValue());
            memberService.updateById(member);
            // 插入积分日志表
            UmsIntegrationChangeHistory historyChange = new UmsIntegrationChangeHistory(member.getId(), new Date(), AllEnum.ChangeType.Min.code(), gifts.getPrice().intValue()
                    , member.getUsername(), order.getId() + "", AllEnum.ChangeSource.order.code());
            integrationChangeHistoryMapper.insert(historyChange);
            // 删除订单缓存
            String key = Rediskey.orderDetail + "orderid" + order.getId();
            redisService.remove(key);

        }
        return new CommonResult().success("兑换成功");
    }
}
